package jam.UserInterface.UI;
import javax.imageio.ImageIO;
import javax.swing.*;
import jam.network.*;
import jam.network.message.*;
import java.io.File;

import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Arrays;


public class loginWindow extends JFrame implements ActionListener,MouseListener,KeyListener {	

	static JFrame mainFrame = new JFrame();
	JButton login, CANCEL, FORGOT, REGISTER;
	JPanel panelLeft, panelCentral,panelBottom, panelUser, panelPassword, panelReg;
	JPanel panelRight;
	JLabel email, pword, registered, empty1;
	final JTextField  username;
	final JPasswordField  password;
	String displayName;

	public loginWindow(){
		
		//optional look and feel
		UIManager.LookAndFeelInfo[] lfi= UIManager.getInstalledLookAndFeels();
		    
		try
		{
		UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		}
		catch (Exception e)
		{
		System.out.println("Can't set chosen look-and-feel!");
	    }

		mainFrame.setDefaultLookAndFeelDecorated(true);

		//sets up the mainframe
		
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		mainFrame.setBounds(((int)(screenSize.getWidth()-600))/2,((int)(screenSize.getHeight()-400))/2,600,400);
		mainFrame.setTitle("JAM -Login");
		mainFrame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);

		//change the icon code
		String currentDirectory = System.getProperty("user.dir");
		try {
			Image image = ImageIO.read(new File(currentDirectory + "/src/jam/UserInterface/Icons/JAMicon.png"));
			mainFrame.setIconImage(image);
		}catch (Exception e){System.out.println("The file could not be read!!!!");}
		
		empty1 = new JLabel();
		empty1.setText("Welcome to the Jam instant messaging system. Things are going to get jammy.");

		email = new JLabel();
		email.setText("Your email:");
		final String init = "Username";
		username = new JTextField(init,20);
		username.setForeground(Color.GRAY);
		username.addMouseListener(this);
		username.addKeyListener(this);


		panelUser = new JPanel(new FlowLayout());
		panelUser.add(email);
		panelUser.add(username);

		pword = new JLabel();
		pword.setText("Password:");
		password = new JPasswordField(20);
		password.addKeyListener(this);

		panelPassword= new JPanel(new FlowLayout());
		panelPassword.add(pword);
		panelPassword.add(password);		  

		registered= new JLabel();
		registered.setText("Not registered yet?    ");

		login =new JButton("Login");
		login.addKeyListener(this);
		FORGOT = new JButton("Forgot something?");
		CANCEL=new JButton("CANCEL");
		CANCEL.addActionListener(this);
		REGISTER = new JButton("Register Now!"); 
		REGISTER.addActionListener(this);

		panelCentral=new JPanel(new GridBagLayout());
		GridBagConstraints c = new GridBagConstraints();
		panelCentral.add(panelUser,c);
		c.gridy=2;
		panelCentral.add(panelPassword,c);

		panelRight = new JPanel(new GridLayout(3,2));

		panelRight.add(empty1);
		panelReg = new JPanel(new FlowLayout());
		panelReg.add(registered);
		panelReg.add(REGISTER);
		panelRight.add(panelReg);		  		  
		panelRight.add(new JSeparator(SwingConstants.HORIZONTAL));


		panelBottom = new JPanel(new FlowLayout());
		panelBottom.add(CANCEL);
		panelBottom.add(FORGOT);
		panelBottom.add(login);
		
		JPanel panelLeft = new JPanel(new FlowLayout());
		try{
			BufferedImage myPicture = ImageIO.read(new File(currentDirectory +"/src/jam/UserInterface/Icons/jam.png"));	
			JLabel picLabel = new JLabel(new ImageIcon( myPicture ));
			panelLeft.add( picLabel );
		}catch (Exception e){ System.out.println("The file wasn't there!!!");}

		mainFrame.add(panelCentral,BorderLayout.CENTER);
		mainFrame.add(panelRight, BorderLayout.NORTH);
		mainFrame.add(panelBottom,BorderLayout.SOUTH);
		mainFrame.add(panelLeft,BorderLayout.WEST);
		
		login.addActionListener(this);
		login.addMouseListener(this);
		mainFrame.setVisible(true);
	}


	public void actionPerformed(ActionEvent e){		
		if (e.getSource() == login){
			String usernameValue=username.getText();
			char[] passwordValue=password.getPassword();
			
			int top = usernameValue.indexOf("@");
			int bot = usernameValue.lastIndexOf(".");		
			boolean un = top > 1 && bot > top + 3 && (bot + 3 == usernameValue.length() || bot + 4 == usernameValue.length());
			
			
			
			if (un && passwordValue.length>=1) {
				displayName = username.getText().substring(0,username.getText().indexOf("@"));
				mainFrame.dispose();
				ClientActionLogin login = new ClientActionLogin(usernameValue, password.getText());
				NetworkController.send( login.toString());
			}
			else{
				System.out.println("enter the valid username and password");
				JOptionPane.showMessageDialog(this,"Login unsuccessful. Please try again.",
						"Error",JOptionPane.ERROR_MESSAGE);
			}
		}
		
		if (e.getSource() == REGISTER){
			SwingUtilities.invokeLater(new Runnable(){
				public void run(){
					new registrationWindow(); // creates the user interface
				}
			});
			mainFrame.dispose();
		}
		
		if (e.getSource() == CANCEL){
			mainFrame.dispose();
		}

	}

	public static void main(String arg[]){
		SwingUtilities.invokeLater(new Runnable(){
			public void run(){
				new loginWindow(); // creates the user interface
			}
		});
	}


	@Override
	public void keyPressed(KeyEvent e) {
		// TODO Auto-generated method stub
		if (e.getSource() == username && e.getKeyCode() == KeyEvent.VK_TAB){
			password.moveCaretPosition(0);
		}
		else if (e.getSource() == password && e.getKeyCode() == KeyEvent.VK_TAB){
			login.setFocusable(true);
		}
		else if (e.getSource() == login && e.getKeyCode() == KeyEvent.VK_ENTER){
			String usernameValue=username.getText();
			char[] passwordValue=password.getPassword();
			
			int top=usernameValue.indexOf("@");
			int bot=usernameValue.lastIndexOf(".");
			
			boolean un = top>1||bot<top+2||bot+2>=usernameValue.length();
			
			if ( passwordValue.length>1) {
				System.out.println("got here loginwindow");
				mainFrame.dispose();
				displayName = username.getText().substring(0,username.getText().indexOf("@"));
				ClientActionLogin login = new ClientActionLogin(usernameValue, passwordValue.toString());
				NetworkController.send( login.toString());
	
			}
			else{
				System.out.println("enter the valid username and password");
				JOptionPane.showMessageDialog(this,"Login unsuccessful. Please try again.",
						"Error",JOptionPane.ERROR_MESSAGE);
			}
		}
		
	}


	@Override
	public void keyReleased(KeyEvent arg0) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public void keyTyped(KeyEvent arg0) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public void mouseClicked(MouseEvent e) {
		// TODO Auto-generated method stub
		if (e.getSource() == username && username.getText().equals("Username")){
			username.setText("");
			username.setForeground(Color.BLACK);
		}
		if (e.getSource() == login){
			String usernameValue=username.getText();
			char[] passwordValue=password.getPassword();
			
			int top=usernameValue.indexOf("@");
			int bot=usernameValue.lastIndexOf(".");
			
			boolean un = top>1||bot<top+2||bot+2>=usernameValue.length();

			System.out.println(passwordValue.length);
			
			if  (passwordValue.length>=1) {
				System.out.println("got here loginwindow");
				mainFrame.dispose();
				displayName = username.getText().substring(0,username.getText().indexOf("@"));
				ClientActionLogin login = new ClientActionLogin(usernameValue, passwordValue.toString());
				NetworkController.send( login.toString());
				
			}
			else{
				System.out.println("enter the valid username and password");
				JOptionPane.showMessageDialog(this,"Login unsuccessful. Please try again.",
											  "Error",JOptionPane.ERROR_MESSAGE);
			}
		}
	}
	

	@Override
	public void mouseEntered(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public void mouseExited(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public void mousePressed(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public void mouseReleased(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}
}
